<?php namespace nimo\common\models;

use Eloquent;
use Illuminate\Database\Eloquent\Builder;

class SequenceGenerator extends Eloquent {
    protected $table = 'nd_master_sequence';
	protected static $columnSeqName = 'seq_name';
	protected static $columnSeqNo = 'seq_no';
    protected $primaryKey = 'seq_name';
    public $incrementing = false;

	public function key() {
		return $this->getAttribute(static::$columnSeqName);
	}
	public function value() {
		return $this->getAttribute(static::$columnSeqNo);
	}
	public function nextval($amount = 1) {
		$key = $this->key();
		$count = $this->where(static::$columnSeqName, '=', $key)->increment(static::$columnSeqNo, $amount);
		return $this->curval();
	}
	public function curval() {
		$key = $this->key();
		$instance = $this->where(static::$columnSeqName, '=', $key)->first(array(static::$columnSeqNo));
		$seq= $instance->value();
		$this->setAttribute(static::$columnSeqNo, $seq);
		return $seq;
	}
	public static function current($table, array $scopes) {
		$key = json_encode(array_merge(array('table'=>$table), $scopes));
		$attributes = array(static::$columnSeqName=>$key);
		if ( is_null($instance = static::firstByAttributes($attributes))){
			// create
			$instance = new static;
			// set primary key
			$instance->setAttribute(static::$columnSeqName, $key);
			$instance->save();
		}
		return $instance;
	}
}
